<template>
	<div v-loading="tableLoading" class="vip-detail-balance-record">
		<!-- 卡片 -->
		<div class="balance-card">
			<el-row :gutter="10">
				<el-col :xs="12" :sm="12" :md="12" :lg="8">
					<div class="app-main-content-box"><ThreePointCard :data="cardData_1" /></div>
				</el-col>
				<el-col :xs="12" :sm="12" :md="12" :lg="8">
					<div class="app-main-content-box"><ThreePointCard :data="cardData_2" /></div>
				</el-col>
				<el-col :xs="12" :sm="12" :md="12" :lg="8">
					<div class="app-main-content-box"><ThreePointCard :data="cardData_3" /></div>
				</el-col>
			</el-row>
		</div>

		<div class="app-main-content-box">
			<!-- 筛选 -->
			<div class="filter">
				<!-- 筛选 -->
				<div class="app-main-filter-collapse-box filter">
					<el-collapse>
						<el-collapse-item ref="filterCollapse" title="按条件筛选" name="1">
							<el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
								<el-form-item label="选择时间：" prop="date">
									<!-- :rules="[
                  { required: true, message: '时间区间不能为空'}
                  ]"-->
									<el-date-picker
										v-model="filterForm.date"
										type="datetimerange"
										range-separator="~"
										value-format="yyyy-MM-dd HH:mm:ss"
										start-placeholder="开始日期"
										end-placeholder="结束日期"
										format="yyyy-MM-dd HH:mm:ss"
										:default-time="['00:00:00', '23:59:59']"
									/>
								</el-form-item>
								<el-form-item label="业务单号：" prop="bizOrderNo">
									<el-input v-model="filterForm.bizOrderNo" placeholder="请输入业务单号" style="width:400px;" />
								</el-form-item>
								<el-form-item label="门店：" prop="shopId">
									<el-select v-model="filterForm.shopId" filterable placeholder="可通过名称搜索" style="width:400px">
										<el-option v-for="(item, index) in $store.state.user.allManageShopFilterOptions" :key="index" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
								<!-- <el-form-item label="终端：" prop="deviceId">
									<el-select v-model="filterForm.deviceId" filterable placeholder="可通过终端名/终端编号搜索" style="width:400px">
										<template v-for="item in $store.state.user.allManageDeviceFilterOptions">
											<el-option
												v-if="filterForm.shopId === '' || item.shopId == filterForm.shopId || item.kdDeviceNo == ''"
												:key="item.id"
												:label="item.kdDeviceNo === '' ? item.deviceName : item.deviceName + '(' + item.kdDeviceNo + ')'"
												:value="item.kdDeviceNo"
											/>
										</template>
									</el-select>
								</el-form-item> -->
								<el-form-item label="变动类型：" prop="recordTypes">
									<el-checkbox
										v-model="checkAllRecordTypes"
										:indeterminate="isIndeterminateRecordTypes"
										class="fl check-all"
										@change="handlecheckAllRecordTypesChange"
									>
										全选
									</el-checkbox>
									<el-checkbox-group v-model="filterForm.recordTypes" @change="handleCheckRecordTypesChange">
										<el-checkbox v-for="(item, index) in recordTypesCheckOptions" :key="index" :label="item.value">{{ item.label }}</el-checkbox>
									</el-checkbox-group>
								</el-form-item>
								<!-- <el-form-item label="业务类型：" prop="bizCode">
									<el-radio-group v-model="filterForm.bizCode">
										<el-radio label="all">全部</el-radio>
										<el-radio v-for="(item, index) in manageBizCodeOptions" :key="index" :label="item.key">{{ item.label }}</el-radio>
									</el-radio-group>
								</el-form-item> -->
								<!-- <el-form-item label="业务来源：" prop="sourceCode">
									<el-radio-group v-model="filterForm.sourceCode">
										<el-radio label="all">全部</el-radio>
										<template v-for="(item, index) in sourceCodeOptions">
											<el-radio :key="index" :label="item.key">{{ item.label }}</el-radio>
										</template>
									</el-radio-group>
								</el-form-item> -->
								<!-- <el-form-item label="支付方式：" prop="payment">
									<el-radio-group v-model="filterForm.payment">
										<el-radio label="all">全部</el-radio>
										<el-radio v-for="item in paymentOptions" :key="item.key" :label="item.key">{{ item.label }}</el-radio>
									</el-radio-group>
								</el-form-item> -->
								<el-form-item class="filter-btn">
									<el-button type="primary" round @click="submitForm('filterForm')">查 询</el-button>
									<el-button round @click="resetForm('filterForm')">重 置</el-button>
								</el-form-item>
							</el-form>
						</el-collapse-item>
					</el-collapse>
				</div>
			</div>

			<!-- 列表 -->
			<div class="balance-table">
				<el-table size="small" :data="list" stripe border style="width: 100%" empty-text="暂无数据">
					<el-table-column prop="createTime" label="变动时间" fixed="left" width="150" />
					<el-table-column prop="bizOrderNo" label="业务单号" fixed="left" width="150" />
					<el-table-column prop="recordType" label="变动类型">
						<template slot-scope="scope">
							<div>
								{{
									scope.row.recordType === 1
										? '充值'
										: scope.row.recordType === 2
										? '赠送'
										: scope.row.recordType === 3
										? '消费'
										: scope.row.recordType === 4
										? '退款'
										: scope.row.recordType === 5
										? '扣除'
										: scope.row.recordType === 6 || scope.row.recordType === 7
										? '人工客服'
										: '无'
								}}
							</div>
						</template>
					</el-table-column>
					<!-- <el-table-column prop="bizName" label="业务类型" /> -->
					<!-- <el-table-column prop="sourceName" label="业务来源" /> -->
					<el-table-column prop="payment" label="支付方式">
						<template slot-scope="scope">
							<div>
								{{
									scope.row.payment === 1
										? '微信'
										: scope.row.payment === 2
										? '余额'
										: scope.row.payment === 3
										? '支付宝'
										: scope.row.payment === 4
										? '银联'
										: scope.row.payment === 5
										? '现金'
										: scope.row.payment === 6
										? '花呗'
										: scope.row.payment === 7
										? '云闪付'
										: '无'
								}}
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="balanceFee" label="变动金额(元)">
						<template slot-scope="scope">
							<div v-if="Number(scope.row.balanceFee) == 0">{{ Number(scope.row.balanceFee / 100) }}</div>
							<div v-else :class="scope.row.balanceFee > 0 ? 'app-text-color-danger' : 'app-text-color-success'">
								{{ scope.row.balanceFee > 0 ? '+' + scope.row.balanceFee / 100 : scope.row.balanceFee / 100 }}
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="balance" label="变动后总余额(元)">
						<template slot-scope="scope">
							<span>{{ scope.row.balance / 100 }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="shopName" label="门店">
						<template slot-scope="scope">
							<span>{{ scope.row.shopName ? scope.row.shopName : '总部' }}</span>
						</template>
					</el-table-column>
					<!-- <el-table-column prop="device" label="消费终端" /> -->
					<el-table-column prop="operatorName" label="操作人" />
					<!-- <el-table-column prop="promoter" label="推广人" /> -->
					<el-table-column prop="remark" label="业务备注" />
				</el-table>
				<!-- 分页 -->
				<pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="sizesChange" @pagechange="pageChange" />
			</div>
		</div>
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getVipAccountInfo } from '@/api/vip';
import { getBalanceRecordsList, getBalanceRecordStatistic } from '@/api/statement';
import { balanceStatistics, getBalanceRecord } from '@/api/UserCenter';
// 组件
import ThreePointCard from './ThreePointCard';
export default {
	components: {
		ThreePointCard
	},
	props: {
		activeName: {
			type: String,
			require: true
		},
		vipDetail: {
			type: Object,
			require: true
		}
	},
	data() {
		return {
			// 配置
			paginationConfig: {
				// 分页配置
				direction: 'center', // 分页位置
				layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
				pageSizes: [10, 20], // 分页pages
				total: 0,
				page: 1, // 页数-默认1
				pageSize: 10 // 每页条数-默认10
			},
			recordTypesCheckOptions: [
				{
					label: '充值',
					value: 1
				},
				{
					label: '充值赠送',
					value: 2
				},
				{
					label: '消费',
					value: 3
				},
				{
					label: '消费退款',
					value: 4
				},
				{
					label: '人工客服',
					value: 6
				}
			],
			recordTypesOptions: [1, 2, 3, 4, 6],
			// 状态
			tableLoading: false, // 表格loading
			checkAllRecordTypes: true, // recordType 多选状态
			isIndeterminateRecordTypes: false, // recordType
			// 数据
			cardData_1: ['总余额', 0, '累计获得', 0, '累计消费', 0],
			cardData_2: ['实充余额', 0, '累计充值', 0, '累计消费', 0],
			cardData_3: ['赠送余额', 0, '累计赠送', 0, '累计消费', 0],
			filterForm: {
				date: [],
				shopId: '',
				recordTypes: [1, 2, 3, 4, 6],
				bizOrderNo: '',
				deviceId: '',
				bizCode: 'all',
				sourceCode: 'all',
				payment: 'all'
			},
			list: [] // 表格数据
		};
	},
	computed: {
		...mapGetters(['manageBizCodeOptions', 'sourceCodeOptions', 'paymentOptions']),
		shopId() {
			return this.filterForm.shopId;
		}
	},
	watch: {
		activeName(val) {
			if (val === 'balance') {
				this.fetchData();
			}
		},
		shopId(newValue, oldValue) {
			this.filterForm.deviceId = '';
		}
	},
	mounted() {
		this.$store.dispatch('GetManageDevice'); // 获取终端
	},
	methods: {
		/**
		 *  获取数据
		 */
		// 获取数据
		fetchData(page = this.paginationConfig.page, pageSize = this.paginationConfig.pageSize) {
			this.$refs.filterForm.validate(async valid => {
				if (valid) {
					// 请求数据
					const params = await this.setRequestParams();
					params.pageNum = page;
					params.pageSize = pageSize;
					params.pubDomainCustomerId = this.vipDetail.customerId;
					const statisticParams = {};
					// statisticParams.memberId = params.memberId
					statisticParams.pubDomainCustomerId = this.vipDetail.customerId;
					this.tableLoading = true;
					Promise.all([this.getTotal(statisticParams), this.getRecord(params)]).then(() => {
						this.tableLoading = false;
					});
				}
			});
		},

		// 获取请求筛选数据
		setRequestParams() {
			return new Promise((resolve, reject) => {
				const filterForm = JSON.stringify(this.filterForm);
				const params = JSON.parse(filterForm)
				// params.beginTimestamp = params.date ? this.$momentMini(params.date[0]).unix() : '';
				// params.endTimestamp = params.date ? this.$momentMini(params.date[1]).unix() : '';
				params.startTime = params.date ? params.date[0] : '';
				params.endTime = params.date ? params.date[1] : '';
				delete params.date;
				// params.memberId = this.vipDetail.member.id
				// 清除多余字段
				for (const key in params) {
					if (params[key] === '' || params[key] === 'all') {
						delete params[key];
					}
				}

				//人工客服充值和人工客服赠送
				if (params.recordTypes.indexOf(7) !== -1) {
					params.recordTypes.splice(params.recordTypes.indexOf(7), 1);
				}
				if (params.recordTypes.indexOf(6) !== -1) {
					params.recordTypes.push(7);
				}
				resolve(params);
			});
		},

		// 获取统计
		getTotal(statisticParams) {
			return new Promise((resolve, reject) => {
				balanceStatistics(statisticParams)
					.then(res => {
						this.setCardTotal(res.data);
					})
					.catch(err => {})
					.finally(() => {
						resolve();
					});
			});
		},

		// 获取记录
		getRecord(params) {
			if (params.bizOrderNo) {
				delete params.beginTimestamp;
				delete params.endTimestamp;
			}
			return new Promise((resolve, reject) => {
				getBalanceRecord(params)
					.then(res => {
						this.list = res.data.list;
						this.paginationConfig.total = res.data.total;
						this.paginationConfig.page = res.data.pageNum;
					})
					.catch(err => {})
					.finally(() => {
						resolve();
					});
			});
		},

		setCardTotal(data) {
			// 赋值卡片一  总
			this.cardData_1.splice(1, 1, this.$options.filters.parseNumberToThousands(data.balance)); // 余额
			this.cardData_1.splice(3, 1, this.$options.filters.parseNumberToThousands(data.balanceSum)); // 累计获得
			this.cardData_1.splice(5, 1, this.$options.filters.parseNumberToThousands(data.balanceSumConsume)); // 累计消费
			this.cardData_1.splice(7, 1, this.$options.filters.parseNumberToThousands(data.totalFrozen)); // 冻结金额
			// 赋值卡片二 实充
			this.cardData_2.splice(1, 1, this.$options.filters.parseNumberToThousands(data.realAccount)); // 实充余额
			this.cardData_2.splice(3, 1, this.$options.filters.parseNumberToThousands(data.realSumRecharge)); // 累计充值
			this.cardData_2.splice(5, 1, this.$options.filters.parseNumberToThousands(data.realSumConsume)); // 累计消费
			this.cardData_2.splice(7, 1, this.$options.filters.parseNumberToThousands(data.realFrozen)); // 冻结金额
			// 赋值卡片三 赠送
			this.cardData_3.splice(1, 1, this.$options.filters.parseNumberToThousands(data.giveAccount)); // 赠送余额
			this.cardData_3.splice(3, 1, this.$options.filters.parseNumberToThousands(data.giveSumRecharge)); // 累计赠送
			this.cardData_3.splice(5, 1, this.$options.filters.parseNumberToThousands(data.giveSumConsume)); // 累计消费
			this.cardData_3.splice(7, 1, this.$options.filters.parseNumberToThousands(data.givenFrozen)); // 冻结金额
		},

		// 分页sizes改变
		sizesChange() {
			this.fetchData();
		},

		// 分页page改变
		pageChange() {
			this.fetchData();
		},

		/**
		 * 按钮
		 */
		// 查询
		submitForm() {
			this.fetchData(1);
		},

		// 重置
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.checkAllRecordTypes = true; // recordType 多选状态
			this.isIndeterminateRecordTypes = false; // recordType
		},

		/**
		 * 状态
		 */
		// checkAllRecordType多选状态
		handlecheckAllRecordTypesChange(val) {
			if (val) {
				this.filterForm.recordTypes = this.recordTypesOptions;
				this.checkAllRecordTypes = true;
			} else {
				this.filterForm.recordTypes = [];
				this.checkAllRecordTypes = false;
			}
			this.isIndeterminateRecordTypes = false;
		},

		handleCheckRecordTypesChange(value) {
			const checkedLength = value.length;
			const maxLength = this.recordTypesOptions.length;
			this.checkAllRecordTypes = checkedLength === maxLength;
			this.isIndeterminateRecordTypes = checkedLength > 0 && checkedLength < maxLength;
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.vip-detail-balance-record {
	/* 卡片 */
	.balance-card {
		.app-main-content-box {
			margin-bottom: 10px;
		}
	}
	/* 重置多选左边距 */
	.el-checkbox + .el-checkbox {
		margin-left: 0;
	}
	.el-checkbox {
		margin-right: 10px;
	}
}

/* 筛选 */
.filter {
	.filter-btn {
		margin-bottom: 20px;
	}
	.check-all {
		margin-right: 30px;
	}
	.el-select {
		width: 120px;
	}
	.input-with-select {
		width: 400px;
	}
	// 换行
	.el-radio + .el-radio {
		margin-left: 0;
	}
	.el-radio {
		margin-right: 10px;
		height: 32px;
		line-height: 32px;
	}
}
</style>
